﻿/*******************************************************************************************
 * Copyright (c) 2006-2009 Alex Robson, Rob Simmons, Craig Israel, and Rachel Twyford
 *
 * Use of this software in any form requires that you have both 
 * read and agreed to the following terms:
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions: 
 *
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the 
 * documentation and/or other materials provided with the distribution.
 * Neither the name of Nvigorate nor the names of its contributors may 
 * be used to endorse or promote products derived from this software without 
 * specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ****************************************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Nvigorate.Aspect;
using Nvigorate.Common;
using Nvigorate.Common.Reflection;

namespace Nvigorate.Relational.State
{
    [DataContract]
    [Serializable]
    public class StateInformation : IPersistenceState
    {
        #region Fields

        protected List<string> _loaded = new List<string>();
        protected List<Tuple<string, object>> _changed = new List<Tuple<string, object>>();
        
        protected List<string> _keys = new List<string>();
        protected bool _relationshipChanged = false;
        protected string _repositoryName;

        #endregion

        #region Properties

        [DataMember]
        public virtual List<string> Loaded
        {
            get { return _loaded; }
            set { _loaded = value; }
        }

        public virtual bool IsDirty
        {
            get { return _changed.Count > 0 || _relationshipChanged; }
        }

        /// <summary>
        /// A flag to indicate that this object is a new instance/new record for the repository
        /// </summary>
        public virtual bool IsNew
        {
            get { return _loaded.Count == 0; }
        }

        [DataMember]
        public virtual List<Tuple<string, object>> ChangedValues
        {
            get { return _changed; }
            set { _changed = value; }
        }

        [DataMember]
        public virtual List<string> Keys
        {
            get { return _keys; }
            set { _keys = value; }
        }

        [DataMember]
        public virtual bool RelationshipChanged
        {
            get { return _relationshipChanged; }
            set { _relationshipChanged = value; }
        }

        [DataMember]
        public virtual string RepositoryName
        {
            get { return _repositoryName; }
            set { _repositoryName = value; }
        }

        #endregion
        
        public virtual void AddChangedValue(string changedPropertyName, object originalValue)
        {
            if (!_changed.Exists(t => t.Value1.Equals(changedPropertyName)))
            {
                _changed.Add(Tuple.Create(changedPropertyName, originalValue));
            }
        }

        public virtual object GetOriginalValue(string propertyName, object instance)
        {
            var tuple = _changed.FirstOrDefault(t => t.Value1 == propertyName);
            return tuple == null ? Reflector.Read(instance, propertyName) : tuple.Value2;
        }

        public virtual void ClearDirtyState()
        {
            ChangedValues.Clear();
        }

        public virtual void ForceInsert()
        {
            Loaded.Clear();
        }
    }

    [DataContract]
    [Serializable]
    [KnownType("GetKnownTypes")]
    public class StateTracking : InstanceIdentifier, ITrackState
    {
        private IPersistenceState _info;
        private static List<Type> _knownTypes = new List<Type>();
        private bool _deserializing = false;

        [DataMember]
        public IPersistenceState InstanceState
        {
            get { return _info; }
            set { _info = value; }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public event PropertyChangingEventHandler PropertyChanging;

        public bool Deserializing
        {
            get { return _deserializing; }
            set { _deserializing = value; }
        }

        public virtual void RaisePropertyChanging(string property)
        {
            if (PropertyChanging != null)
                PropertyChanging(this, new PropertyChangingEventArgs(property));
        }
        public virtual void RaisePropertyChanged(string property)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(property));
        }

        public static Type[] GetKnownTypes()
        {
            if (_knownTypes.Count == 0)
            {
                new StateTracking().PopulateKnownTypes();
                _knownTypes.Add(typeof(StateInformation));
                _knownTypes.Add(typeof(InstanceIdentifier));
            }
            return _knownTypes.ToArray();
        }

        private void PopulateKnownTypes()
        {
            _knownTypes = Reflector.GetPropertyInfoList(this.GetType()).Select(p => p.PropertyType).ToList();
        }

        [OnDeserializing]
        public void OnDeserializing(StreamingContext context)
        {
            _deserializing = true;
        }

        [OnDeserialized]
        public void OnDeserialized(StreamingContext context)
        {
            _deserializing = false;
        }

        public StateTracking()
        {
            _info = new StateInformation();
        }
    }
}